package com.google.code.sip.ucenter.web.admin.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.sip.core.dao.Page;
import com.google.code.sip.core.utils.WebGridUtils;
import com.google.code.sip.ucenter.model.Application;
import com.google.code.sip.ucenter.service.ApplicationManager;

@Controller
public class ApplicationController {

	@Autowired
	private ApplicationManager applicationManager;

	@RequestMapping("/admin/application.do")
	public ModelAndView index(HttpServletRequest request) {
		return list(request);
	}

	@RequestMapping("/admin/application!list.do")
	public ModelAndView list(HttpServletRequest request) {
		Page<Application> page = new Page<Application>();

		WebGridUtils.fillPage(request, page);
		applicationManager.findApplications(page);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("totalRows", (int) page.getTotalCount());
		model.put("page", page);
		return new ModelAndView("admin.application.list", model);
	}

	@RequestMapping("/admin/application!edit.do")
	public ModelAndView edit(@RequestParam("id") String id) {
		Application application = null;
		if (StringUtils.isNotEmpty(id)) {
			application = applicationManager.getApplication(id);
		} else {
			application = new Application();
		}
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("application", application);
		return new ModelAndView("admin.application.edit", model);
	}

	@RequestMapping("/admin/application!save.do")
	public ModelAndView save(
			@ModelAttribute("application") Application application,
			HttpServletRequest request) {
		applicationManager.saveApplication(application);
		return list(request);
	}

	@RequestMapping("/admin/application!delete.do")
	public ModelAndView delete(@RequestParam("id") String id,
			HttpServletRequest request) {
		applicationManager.deleteApplication(id);
		return list(request);
	}
}
